<template>
  <div>
    <cfg-table ref="table" :columns="columns" :data="data" :loading="loading" :config="tableConfig"
      :pageSizeOpts="pageSizeOpts" :pageNavigation="pageNavigation" :queryFormItem="queryFormItem"
      :collapseFormItem="collapseFormItem" :additionalAction="additionalAction" @loadPage="loadPage"
      @handleCreate="handleCreate" @handleDetail="handleDetail"
      @handleEdit="handleEdit" @handleDelete="handleDelete"
      @handleDeleteMultiple="handleDeleteMultiple" @handleSearch="handleSearch"
      @handleReset="handleReset"
    />
    <CfgModal v-bind="modalConfig" :data="curRowData"
      :drawer="modelDrawer"
      :fields="modalFormItem"
      @submit="handleOk"
    />
    <hierachy-editor :drawer="hierDrawer" :modelType="modelType" :data="hierData" @submit="submitHier" />
  </div>
</template>

<script>
export default {
  name: "crud-select",
  data() {
    let newTplData = this.$modelObject.getTpl(this.modelName);

    return {
      classObject: null,
      collectionObject: null,
      modelDrawer: {
          type: 'new',
          show: false
      },
      curRowData: newTplData,
      newTplData,
      record: {},
      modelType: '',
      hierData: {},
      hierDrawer: {
        show: false,
      },
      loading: false,
      pageSizeOpts: [10, 30, 50, 100],
      pageNavigation: { total: 0, pageSize: 10, pageNumber: 1 },
    }
  },
  props: {
    modelName: {
      default() {
        return ''
      }
    },
    modalNeedQuery: {
      default() {
        return true
      }
    },
    modalConfig: {
      default() {
        return {}
      }
    },
    tableConfig: {
      default() {
        return {}
      }
    },
    columns: {
      default() {
        return []
      }
    },
    queryFormItem: {
      default() {
        return []
      }
    },
    modalFormItem: {
      default() {
        return []
      }
    },
    additionalButtons: {
      default() {
        return []
      }
    },
    collapseFormItem: {
      default() {
        return []
      }
    }
  },
  computed: {
    data() {
      if (!!this.collectionObject) {
        return this.collectionObject.records;
      } else {
        return [];
      }
    },
    additionalAction() {
      let buttons = []
      if (this.tableConfig.additionalAction && this.additionalButtons && this.additionalButtons.length) {
        this.additionalButtons.forEach(item => {
          item.title = item.title[this.G_Locale]
          item.event = (row, index) => {
            return item.eventName && this[item.eventName] ? this[item.eventName](row, index) : ''
          }
          buttons.push(item)
        })
      }
      return {
        key: 'additionalAction',
        title: { 'zh-CN': '附加操作', 'en-US': 'addition action' }[this.G_Locale],
        slot: 'additionalAction',
        width: 100,
        fixed: 'right',
        align: 'center',
        show: this.tableConfig.additionalAction,
        buttons
      }
    }
  },
  created() {
    // console.log("🚀 ~ file: cfgCrud.vue:106 ~ created")
    this.collectionObject = this.$modelObject.create(`${this.modelName}Collection`);
    this.classObject = this.$modelObject.create(this.modelName)
  },
  beforeMount() {
    // console.log("🚀 ~ file: cfgCrud.vue:111 ~ beforeMount")
    this.loadPage(this.pageNavigation, null)
  },
  mounted() {

  },
  methods: {
    loadPage(pageNavigation, filter) {
      let newFilter = "";
      if (this.tools.isReal(filter)) {
        newFilter = this.collectionObject.util.getFilter(filter);
      }
      this.loading = true;
      this.collectionObject.queryInfoByPage(pageNavigation.pageNumber, pageNavigation.pageSize, newFilter).then(flag => {
        if (flag) {
          this.pageNavigation.total = this.collectionObject.total;
          this.loading = false;
        } else {
          this.loading = false;
        }
      })
    },
    getRecord(filter) {
      let newFilter = this.collectionObject.util.getFilter(filter);
      return this.classObject.query(newFilter).then(flag => {
        if (flag) {
          return this.classObject.record;
        } else {
          return false;
        }
      })
    },
    deleteRecord(ids) {
      let _this = this;
      this.loading = true;
      return this.collectionObject.deleteByIds(ids).then(flag => {
        if (flag) {
          ids.forEach(id => {
            let index = _this.collectionObject.records.findIndex(item => item.id === id);
            if (index !== -1) {
              _this.collectionObject.records.splice(index, 1)
            }
          })
          this.loading = false;
          return true;
        } else {
          this.loading = false;
          return false;
        }
      })
    },
    handleSearch(filter) {
      this.pageNavigation.pageNumber = 1;
      this.loadPage(this.pageNavigation, filter)
    },
    handleReset() {
      this.pageNavigation.pageNumber = 1;
      this.loadPage(this.pageNavigation, null)
    },
    handleCreate() {
      // this.$set(this.modelDrawer,'show',true)
      console.log("🚀 ~ file: cfgCrud.vue:176 ~ handleCreate ~ this.curRowData:", this.curRowData)
      this.curRowData = this.newTplData;
      this.modelDrawer.type = 'new'
      this.modelDrawer.show = true
    },
    handleOk(data) {
      console.log("🚀 ~ file: index.vue:201 ~ handleOk ~ data:", this.modelDrawer.type, data)
      
      this.modelDrawer.type === 'edit' && this.handleEditSubmit(data);
      this.modelDrawer.type === 'new' && this.handleNewAddSubmit(data);
    },
    handleNewAddSubmit(data) {
      this.loading = true;
      this.classObject.add(data).then(flag => {
        if (flag) {
          this.collectionObject.records.unshift(this.classObject.record);
          this.loading = false;
          this.modelDrawer.show = false
        } else {
          this.loading = false;
        }
      }).catch(err => {
        console.log("🚀 ~ file: index.vue:218 ~ this.classObject.add ~ err:", err)
        
      })
    },
    async handleEdit(row, index) {
      this.loading = true;

      if (!this.modalNeedQuery) {
        this.curRowData = row
        this.modelDrawer.type = 'edit'
        this.modelDrawer.show = true
        this.loading = false
      } else if (await this.getRecord({ type: row.type, className: row.className })) {
        // this.$set(this.editPanel,'data',this.classObject.record);
        // this.$set(this.editPanel.drawer,'show',true);
        this.curRowData = this.classObject.record;
        this.modelDrawer.type = 'edit'
        this.modelDrawer.show = true
        this.loading = false;
      } else {
        this.loading = false;
      }
    },
    handleEditSubmit(data) {
      this.loading = true;
      this.classObject.setRecord(data);
      this.classObject.update().then(flag => {
        if (flag) {
          let index = this.collectionObject.records.findIndex(item => item.id === this.classObject.record.id);
          if (index !== -1) {
            this.collectionObject.records.splice(index, 1, this.classObject.record)
          }
          this.loading = false;
          this.modelDrawer.show = false
        } else {
          this.loading = false;
        }
      })
    },
    async handleDetail(row, index) {
      this.loading = true;
      if (!this.modalNeedQuery) {
        this.curRowData = row
        this.modelDrawer.type = 'read'
        this.modelDrawer.show = true
        this.loading = false
      }
      else if (await this.getRecord({ type: row.type, className: row.className })) {
        this.curRowData = this.classObject.record;
        this.modelDrawer.type = 'read'
        this.modelDrawer.show = true
        this.loading = false;
      } else {
        this.loading = false;
      }
    },
    handleDelete(row, index) {
      this.deleteRecord([row.id])
    },
    async handleDeleteMultiple(selection) {
      let ids = [];
      selection.map(item => ids.push(item.id));
      await this.deleteRecord(ids).then(flag => {
        if (flag) {
          this.$refs.table.selection = [];
        }
      });
    },
    async actionRegister(row, index) {
      this.record = await this.getRecord({ type: row.type, className: row.className });
      if (!this.record.hier || this.record.hier.length == 0) {
        this.record.hier = [{ basic: [] }];
        if (this.record.type === 'logicSingleton') {
          this.record.hier = [{ basic: [this.$modelObject.getHierTpl()['basic']] }];
        }
      };
      this.modelType = this.record.type;
      this.hierData = this.record.hier[0];
      this.hierDrawer.show = true;
    },
    actionStart(row, index) {
      this.loading = true;
      row.status = row.status === 0 ? 1 : 0;
      this.classObject.setRecord(row);
      this.classObject.quartz().then(flag => {
        if (flag) {
          this.collectionObject.records.splice(index, 1, this.classObject.record)
        }
        this.loading = false;
      })
    },
    submitHier(data) {
      this.record.hier[0] = data;
      this.classObject.setRecord(this.record);
      this.classObject.update().then(flag => {
        if (flag) {
          let index = this.collectionObject.records.findIndex(item => item.id === this.classObject.record.id);
          if (index !== -1) {
            this.collectionObject.records.splice(index, 1, this.classObject.record)
          }
          this.hierDrawer.show = false;
        }
      })
    }
  }

}
</script>

<style scoped></style>
